package meijuli.com.join51.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.SimpleTextWatch;
import meijuli.com.join51.business.activity.SetPayPwdActivity;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.BankMsg;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.Withdraw;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.PayPwdDialog;
import meijuli.com.join51.business.utils.BankUtils;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;

/**
 * 兑换页面
 *
 * @author wenqin 2017-05-05 17:37
 */

public class WithDrawFragment extends BaseFragment {
    public static final String KEY_BANK_MSG = "key_bank_msg";
    TextView mTextBankName;
    ImageView mChangeBank;
    TextView mBankNum;
    TextView mUserName;
    RadioButton mRadioSettle;
    EditText mWithdrawEdit;
    ImageView mIcon;
    RelativeLayout mBankLayout;
    TextView mWithdrawTips;
    TextView mRealPrice;
    Button mExtractBtn;

    private double mExtractFee;
    private String type = "-1";
    private RadioButton mSilverRbtn;
    private double mSelectedPrice = 0;
    private Withdraw mWithdraw;
    private PayPwdDialog mPayPWdDialog;
    private RadioGroup mSettleRg;
    private Call<HttpResponse<Withdraw>> mCall;

    public static WithDrawFragment newInstance(BankMsg bankMsg) {
        Bundle args = new Bundle();
        args.putSerializable(KEY_BANK_MSG, bankMsg);
        WithDrawFragment fragment = new WithDrawFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_withdraw, container, false);
        mTextBankName = view.findViewById(R.id.text_bank_name);
        mChangeBank = view.findViewById(R.id.change_bank);
        mBankNum = view.findViewById(R.id.bank_num);
        mUserName = view.findViewById(R.id.user_name);
        mRadioSettle = view.findViewById(R.id.radio_settle);
        mSilverRbtn = view.findViewById(R.id.radio_silver);
        mWithdrawEdit = view.findViewById(R.id.withdraw_edit);
        mSettleRg = view.findViewById(R.id.rg_settle);
        mIcon = view.findViewById(R.id.icon);
        mBankLayout = view.findViewById(R.id.bank_layout);
        mWithdrawTips = view.findViewById(R.id.withdraw_tips);
        mRealPrice = view.findViewById(R.id.real_price);
        mExtractBtn = view.findViewById(R.id.extract_btn);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        watchWithdrawEdit();

        if (getArguments() != null) {
            BankMsg bankMsg = (BankMsg) getArguments().getSerializable(KEY_BANK_MSG);
            if (bankMsg == null) {
                return;
            }
            mUserName.setText(BankUtils.getRealName(bankMsg.getRealName()));
            mBankNum.setText(BankUtils.getBankCard(bankMsg.getBankCardNum()));
            mTextBankName.setText(bankMsg.getBankName());
            mChangeBank.setVisibility(View.GONE);
            Glide.with(getActivity()).load(bankMsg.getBankCardIco())
                    .error(R.mipmap.bank_logo)
                    .into(mIcon);

            initPayDialog(bankMsg);

            requestWithDrawMsg();
        }

        mSettleRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int id) {
                if(id == R.id.radio_settle) {
                    type = mWithdraw.getGoodsMoneyId();
                    mSelectedPrice = safeConvertDouble(mWithdraw.getGoodsMoney());
                } else {
                    type = mWithdraw.getSilverId();
                    mSelectedPrice = safeConvertDouble(mWithdraw.getSilver());
                }
                checkPrice(mWithdrawEdit.getText().toString());
            }
        });

        mExtractBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                extract();
            }
        });

    }

    private void initPayDialog(BankMsg bankMsg) {
        mPayPWdDialog = new PayPwdDialog(getActivity(), bankMsg);
        mPayPWdDialog.setOnListener(new PayPwdDialog.OnListener() {
            @Override
            public void onInputFinish(CharSequence text) {
                request(text.toString());
            }

            @Override
            public void onForgetClick(View view) {
                Intent intent = new Intent(getActivity(), SetPayPwdActivity.class);
                getActivity().startActivity(intent);
                getActivity().finish();
            }
        });
    }

    private void requestWithDrawMsg() {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class).getWalletMsg();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<Withdraw>() {

            @Override
            public void onSuccess(String url, Withdraw data) {
                dismissDialog();
                mWithdraw = data;
                mRadioSettle.setText(Html.fromHtml("货款： <font color='#ff2d4b'>¥" +
                        mWithdraw.getStringGoodsMoney() + "</font>"));
                mSilverRbtn.setText(Html.fromHtml("银子： <font color='#ff2d4b'>¥" +
                        mWithdraw.getSilver() + "</font>"));
                mWithdrawTips.setText(mWithdraw.getRequire_desc());
                type = mWithdraw.getGoodsMoneyId();
                mSelectedPrice = safeConvertDouble(mWithdraw.getGoodsMoney());
                mExtractFee = mWithdraw.getExtractFee() / 100;
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    private double safeConvertDouble(String strDouble) {
        double value = 0.00;

        try {
            value = Double.parseDouble(strDouble);
        } catch (Exception e) {
            CrashReport.postCatchedException(new Throwable("WithDrawFragment::235 line", e));
        }

        return value;
    }

    /**
     * 兑换输入框监听
     */
    private void watchWithdrawEdit() {

        mWithdrawEdit.addTextChangedListener(new SimpleTextWatch() {
            @Override
            public void afterTextChanged(Editable s) {
                checkPrice(s.toString());

                if (mExtractFee == 0) {
                    mRealPrice.setVisibility(View.GONE);
                    return;
                }
                if (s.length() > 0) {
                    Double price = Double.valueOf(s.toString());
                    double tempPrice = StringUtil.getMultiplyString(price, (1 - mExtractFee));
                    String realPrice = StringUtil.formatAmount(tempPrice, 2);
                    mRealPrice.setText("实际支付：¥ " + realPrice + "");
                } else {
                    mRealPrice.setText("实际支付: ¥ " + 0.00 + "");
                }
            }
        });
    }

    private void checkPrice(String s) {
        if (s.length() > 0) {
            double price = safeConvertDouble(s);
            if (price <= mSelectedPrice && price > 0) {
                mExtractBtn.setEnabled(true);
            } else {
                mExtractBtn.setEnabled(false);
            }
        } else {
            mExtractBtn.setEnabled(false);
        }
    }

    /**
     * 兑换
     */
    private void extract() {
        if (mWithdrawEdit.getText().toString().length() == 0) {
            ToastUtil.getInstance().showToast(getActivity(), "提现金额不能为空");
            return;
        } else if(Double.parseDouble(mWithdrawEdit.getText().toString()) <= 0) {
            ToastUtil.getInstance().showToast(getActivity(), "提现金额必须大于0");
            return;
        } else if(type == mWithdraw.getSilverId() &&
                Double.parseDouble(mWithdrawEdit.getText().toString()) < mWithdraw.getExtract_silver_fee()) {
            ToastUtil.getInstance().showToast(getActivity(), "提现金额必须大于等于" + mWithdraw.getExtract_silver_fee());
            return;
        }
        if(mPayPWdDialog != null && !mPayPWdDialog.isShowing() && !getActivity().isFinishing()) {
            mPayPWdDialog.show();
        }
    }

    private void request(String pwd) {
        ApiManager manager = ApiManager.get();
        showLoadingDialog();
        Call<HttpResponse<Object>> call1 = manager.getApiService(true, ApiService.class)
                .withdraw(mWithdrawEdit.getText().toString(),
                type + "", StringUtil.encodeToSHA256(pwd));
        HttpRequest.getRequest().autoRecycle(this).start(call1, new ResponseCallback<Object>() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                ToastUtil.getInstance().showToast("提现成功~");
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_UPDATE_WALLET));
                getActivity().finish();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                dismissDialog();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPayPWdDialog != null) {
            mPayPWdDialog.dismiss();
        }
    }
}
